//
//  KZGridViewDataSource.swift
//  Fanrengame
//
//  Created by 朱凯 on 2018/4/28.
//  Copyright © 2018年 JooKey. All rights reserved.
//

import UIKit

class KZGridViewDataSource: UICollectionViewFlowLayout, UICollectionViewDelegate, UICollectionViewDataSource {
    
    var items: [[Any]]?
    var headerItems: [Any]?
    
    private weak var grid: UICollectionView!
    
    private var cellConfig: ((AnyObject, IndexPath, Any)->Void)!
    private var cellClass: AnyClass! {
        didSet {
            grid.register(self.cellClass, forCellWithReuseIdentifier: "cell")
        }
    }
    
    private var headerConfig: ((AnyObject, Int, Any)->Void)?
    private var headerClass: AnyClass? {
        didSet {
            guard let headerClass = headerClass else {
                return
            }
            grid.register(headerClass, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "header")
        }
    }
    
    init(grid: UICollectionView) {
        super.init()
        self.grid = grid
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    func registerCell(cellClass: AnyClass, config: @escaping (AnyObject, IndexPath, Any)->Void) {
        self.cellClass = cellClass
        self.cellConfig = config
    }
    func registerHeader(headerClass: AnyClass, config: @escaping (AnyObject, Int, Any)->Void) {
        self.headerClass = headerClass
        self.headerConfig = config
    }
    
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return items?.count ?? 0
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        let itemsAtSection: [Any]? = items?[section]
        return itemsAtSection?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
        let itemsAtSection: [Any]? = items?[indexPath.section]
        cellConfig(cell, indexPath, itemsAtSection![indexPath.row])
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
    
        let header = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier:"header" , for: indexPath)
        headerConfig?(header, indexPath.section, headerItems![indexPath.section])
        return header
    }
   

    

}
